﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows.Forms;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Events;
using Autodesk.Revit.UI;
using YJKCodeBase.WinForm;
using YJKView;

namespace YJKFloor.AutoSplitFloor
{
	[Transaction(TransactionMode.Manual)]
	[Regeneration(RegenerationOption.Manual)]
	public class CmdAutoSplitFloor : IExternalCommand
	{
		public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
		{
			Result result;
			try
			{
				if (commandData == null)
				{
					throw new System.ArgumentNullException("commandData");
				}
				CmdViewType types = (CmdViewType)9;
				if (SwitchView.SetUsableView(types, commandData) != Autodesk.Revit.UI.Result.Succeeded)
				{
					result = Autodesk.Revit.UI.Result.Failed;
				}
				else
				{
					commandData.Application.Application.FailuresProcessing += this.OnFailuresProcessing;
					this.m_Doc = commandData.Application.ActiveUIDocument.Document;
					if (CmdAutoSplitFloor._hWndRevit == null)
					{
						Process currentProcess = Process.GetCurrentProcess();
						IntPtr mainWindowHandle = currentProcess.MainWindowHandle;
						CmdAutoSplitFloor._hWndRevit = new WindowHandle(mainWindowHandle);
					}
					FloorSpliter floorSpliter = new FloorSpliter(commandData);
					Result result2 = floorSpliter.Split(ref message);
					if (result2 != null)
					{
						if (result2 == Autodesk.Revit.UI.Result.Failed)
						{
							MessageBox.Show("无法拆分楼板，楼板未选中或缺少拆分边界。", "盈建科提示");
						}
						result = result2;
					}
					else
					{
						result = Autodesk.Revit.UI.Result.Succeeded;
					}
				}
			}
			catch (Exception)
			{
				result = Autodesk.Revit.UI.Result.Failed;
			}
			return result;
		}

		private void OnFailuresProcessing(object sender, FailuresProcessingEventArgs e)
		{
			FailuresAccessor failuresAccessor = e.GetFailuresAccessor();
			string transactionName = failuresAccessor.GetTransactionName();
			IList<FailureMessageAccessor> failureMessages = failuresAccessor.GetFailureMessages();
			if (failureMessages.Count == 0)
			{
				e.SetProcessingResult((FailureProcessingResult)0);
				return;
			}
			if (transactionName.Equals("new opeing"))
			{
				foreach (FailureMessageAccessor failureMessageAccessor in failureMessages)
				{
					failuresAccessor.ResolveFailure(failureMessageAccessor);
				}
				e.SetProcessingResult((FailureProcessingResult)1);
				return;
			}
			if (transactionName.Equals("new floor"))
			{
				foreach (FailureMessageAccessor failureMessageAccessor2 in failureMessages)
				{
					failuresAccessor.DeleteWarning(failureMessageAccessor2);
				}
				e.SetProcessingResult((FailureProcessingResult)1);
				return;
			}
			e.SetProcessingResult((FailureProcessingResult)0);
		}

		private Document m_Doc;

		public static WindowHandle _hWndRevit;
	}
}
